package com.free.semantic.infrastruct.repository.impl;

import com.free.semantic.infrastruct.common.ModelMarketDO;
import com.free.semantic.infrastruct.common.ModelMarketRelDO;
import com.free.semantic.infrastruct.mapper.ModelMarketMapper;
import com.free.semantic.infrastruct.mapper.ModelMarketRelMapper;
import com.free.semantic.infrastruct.repository.ModelMarketRepository;
import com.free.semantic.infrastruct.repository.ModelRepository;
import com.free.semantic.model.conceptmodel.Model;
import com.free.semantic.model.conceptmodel.ModelMarket;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 模型市场Repository实现类
 */
@Repository
public class ModelMarketRepositoryImpl implements ModelMarketRepository {

    @Autowired
    private ModelMarketMapper modelMarketMapper;
    
    @Autowired
    private ModelMarketRelMapper modelMarketRelMapper;
    
    @Autowired
    private ModelRepository modelRepository;

    @Override
    public ModelMarket findById(Long id) {
        ModelMarketDO marketDO = modelMarketMapper.findById(id);
        if (marketDO == null) {
            return null;
        }
        
        ModelMarket market = convertToModel(marketDO);
        // 加载关联的模型
        List<Model> models = findModelsByMarketId(id);
        market.setModels(models);
        
        return market;
    }

    @Override
    public List<ModelMarket> findAll() {
        List<ModelMarketDO> marketDOs = modelMarketMapper.findAll();
        return marketDOs.stream()
                .map(this::convertToModel)
                .collect(Collectors.toList());
    }

    @Override
    @Transactional
    public Long save(ModelMarket modelMarket) {
        ModelMarketDO marketDO = convertToDO(modelMarket);
        modelMarketMapper.insert(marketDO);
        Long marketId = marketDO.getId();
        
        // 保存关联的模型
        if (modelMarket.getModels() != null && !modelMarket.getModels().isEmpty()) {
            for (Model model : modelMarket.getModels()) {
                // 确保模型已保存
                Long modelId = model.getId();
                if (modelId == null) {
                    modelId = modelRepository.save(model);
                }
                
                // 添加关联
                addModelToMarket(marketId, modelId);
            }
        }
        
        return marketId;
    }

    @Override
    @Transactional
    public void update(ModelMarket modelMarket) {
        ModelMarketDO marketDO = convertToDO(modelMarket);
        modelMarketMapper.update(marketDO);
    }

    @Override
    @Transactional
    public void deleteById(Long id) {
        // 先删除关联
        modelMarketRelMapper.deleteByMarketId(id);
        // 再删除市场
        modelMarketMapper.deleteById(id);
    }

    @Override
    @Transactional
    public void addModelToMarket(Long marketId, Long modelId) {
        // 检查关联是否已存在
        List<ModelMarketRelDO> existingRels = modelMarketRelMapper.findByMarketId(marketId);
        boolean exists = existingRels.stream()
                .anyMatch(rel -> rel.getModelId().equals(modelId));
        
        if (!exists) {
            ModelMarketRelDO relDO = new ModelMarketRelDO();
            relDO.setMarketId(marketId);
            relDO.setModelId(modelId);
            modelMarketRelMapper.insert(relDO);
        }
    }

    @Override
    @Transactional
    public void removeModelFromMarket(Long marketId, Long modelId) {
        modelMarketRelMapper.deleteByModelIdAndMarketId(modelId, marketId);
    }

    @Override
    public List<Model> findModelsByMarketId(Long marketId) {
        List<ModelMarketRelDO> rels = modelMarketRelMapper.findByMarketId(marketId);
        List<Model> models = new ArrayList<>();
        
        for (ModelMarketRelDO rel : rels) {
            Model model = modelRepository.findById(rel.getModelId());
            if (model != null) {
                models.add(model);
            }
        }
        
        return models;
    }

    @Override
    public List<ModelMarket> findMarketsByModelId(Long modelId) {
        List<ModelMarketRelDO> rels = modelMarketRelMapper.findByModelId(modelId);
        List<ModelMarket> markets = new ArrayList<>();
        
        for (ModelMarketRelDO rel : rels) {
            ModelMarketDO marketDO = modelMarketMapper.findById(rel.getMarketId());
            if (marketDO != null) {
                markets.add(convertToModel(marketDO));
            }
        }
        
        return markets;
    }

    /**
     * 将DO转换为Model
     */
    private ModelMarket convertToModel(ModelMarketDO marketDO) {
        if (marketDO == null) {
            return null;
        }
        
        ModelMarket market = new ModelMarket();
        market.setId(marketDO.getId());
        market.setName(marketDO.getName());
        market.setDescription(marketDO.getDescription());
        market.setModels(new ArrayList<>());
        
        return market;
    }

    /**
     * 将Model转换为DO
     */
    private ModelMarketDO convertToDO(ModelMarket market) {
        if (market == null) {
            return null;
        }
        
        ModelMarketDO marketDO = new ModelMarketDO();
        marketDO.setId(market.getId());
        marketDO.setName(market.getName());
        marketDO.setDescription(market.getDescription());
        
        return marketDO;
    }
} 